package xyz.poke.business.tool.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import xyz.poke.business.tool.common.PageResult;
import xyz.poke.business.tool.constants.DbConstants;
import xyz.poke.business.tool.dto.GoodsDTO;
import xyz.poke.business.tool.entity.Category;
import xyz.poke.business.tool.entity.Goods;
import xyz.poke.business.tool.mapper.GoodsMapper;
import xyz.poke.business.tool.param.GoodsParam;
import xyz.poke.business.tool.service.ICategoryService;
import xyz.poke.business.tool.service.IGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品基本信息表 服务实现类
 * </p>
 *
 * @author 迫壳
 * @since 2024-02-22
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private ICategoryService categoryService;

    @Override
    public PageResult<GoodsDTO> paging(GoodsParam param) {
        PageResult<GoodsDTO> result = new PageResult<>();
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<Goods>().eq(DbConstants.IS_DEL, false);
        if (StringUtils.isNotBlank(param.getSearchField())) {
            goodsQueryWrapper.eq(DbConstants.NAME, param.getSearchField());
        }
        Page<Goods> page = this.page(new Page<>(param.getPageNum(), param.getPageSize()), goodsQueryWrapper);
        BeanUtils.copyProperties(page, result);
        if (result.isEmpty()) {
            return result;
        }
        List<Integer> categoryIds = result.getRecords().stream().map(GoodsDTO::getCategoryId).filter(Objects::nonNull)
                .distinct().collect(Collectors.toList());
        List<Category> categories = categoryService.listByIds(categoryIds);
        Map<Integer, String> categoryNameOfIdMap = categories.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        result.getRecords().forEach(goodsDTO ->
                goodsDTO.setCategoryName(categoryNameOfIdMap.getOrDefault(goodsDTO.getCategoryId(), StringUtils.EMPTY)));
        return result;
    }
}
